#include<stdlib.h>
#include<stdio.h>
#include"mystdio.h"
#include <sys/types.h>
 #include <sys/stat.h>
#include<unistd.h>
#include<assert.h>
#include <fcntl.h>
#define permission 0666
  _FILE*_fopen(const char*filename,const char*mode)
{
  assert(filename);
  assert(mode);
  int m = 0;
  int fd=-1;
  if(strcmp(mode,"w")==0)
  {
    m=(O_CREAT|O_WRONLY|O_TRUNC);
    fd=open(filename,m,permission);
  }
 else if(strcmp(mode,"a")==0)
  {
    m=(O_CREAT|O_WRONLY|O_APPEND);
    fd=open(filename,m,permission);
  }
 else if(strcmp(mode,"r")==0)
  {
    m=O_RDONLY;
    fd=open(filename,m);
  }
 else 
 {
   return NULL;
 }
 if(fd==-1)
 {
   return NULL;
 }
 _FILE*fp=(_FILE*)malloc(sizeof(_FILE));
 if(fp==NULL)
   return NULL;
 fp->fileno=fd;
  fp->outpos=0;
  fp->flag=flush_line;
 return fp;
}

int _fwrite(_FILE*fp,const char*str,int len)
{
  memcpy(&fp->outbuffer[fp->outpos],str,len);//没有做异常处理
  fp->outpos+=len;
  if(fp->flag&flush_line)
  {
    if(fp->outbuffer[fp->outpos-1]=='\n')
    {
      write(fp->fileno,fp->outbuffer,fp->outpos);
      fp->outpos=0;
    } 
    else 
    {
        return len;
    }
  }
  else if(fp->flag & flush_now)
  {
     write(fp->fileno,fp->outbuffer,fp->outpos);
      fp->outpos=0;
  }
  else if(fp->flag & flush_all)
  {
    if(fp->outpos==size)
    {
   
     write(fp->fileno,fp->outbuffer,fp->outpos);
      fp->outpos=0;
    }
  }
  return len;
 }
void _fflush(_FILE*fp)

{
  if(fp->outpos>0)
    write(fp->fileno,fp->outbuffer,fp->outpos);
  fp->outpos=0;
}
void _fclose(_FILE*fp)
{
  if(fp==NULL) return;
  _fflush(fp);
  close(fp->fileno);
  free(fp);
}
